import { BOTH_GOAL, initialState, MAO_CAI_SHEN } from "../../const/index";
import { findElementByTextDFS } from "../index";

export const getWordAndKey = (textToN: string, zhuboMapWords: Record<string, string[]>, noReal2RealMaps: Record<string, string>) => {
  let findWord;
  let findKey;
  for (const key in zhuboMapWords) {
    const words = zhuboMapWords[key];
    findWord = words?.find((word) => {
      if (
        textToN.includes("双进") &&
        noReal2RealMaps[word] === BOTH_GOAL) {
        return true;
      } else {
        return word === textToN;
      }
    });
    if (findWord) {
      findKey = key;
      break;
    }
  }

  return {
    findWord,
    findKey,
  };
}

export const getOrderMoney = (text: string) => {
  if (initialState.zhuboming === MAO_CAI_SHEN) {
    let pay = 10;
    const str = text?.split("】")?.[1];
    const numberRegex = /(\d+)/;
    let matchNumber = str?.match(numberRegex);
    if (matchNumber) {
      pay =
        (Number(matchNumber[0]) < 5 ? 5 : Number(matchNumber[0])) *
        initialState.payBeiShu;
      pay = pay > initialState.payBeiShu * 30 ? initialState.payBeiShu * 30 : pay;
    } else {
      pay = 10 * initialState.payBeiShu;
    }
    return pay
  } else {
    return initialState.dsmpay
  }
}


export const getRightGoal = (num: string) => {
  const str = String(num);
  if (str.includes(".")) {
    // 如果有小数点
    if (str.includes("25") || str.includes("75")) {
      // 0.25 => 0/0.5 0.75 => 0.5/1  1.5/2 2.5/3 1/1.5
      const nStr = `${Number(str) - 0.25}/${Number(str) + 0.25}`;
      return nStr;
    }
    return str;
  }
  return num;
}



export const updateOrders = (orderItems: any[]) => {
  const orders = document.createElement("div");
  orders.id = "orders";
  orders.style.fontSize = '10px';
  if (document.getElementById("orders")) {
    document.getElementById("orders")?.remove();
  }
  orders.innerHTML = orderItems
    .map((item: any) => {
      const { text, key, pay } = item;
      return `<div>盘口：${key}，下单项目：${text}，下单金额：${pay}</div>`;
    })
    .join("");
  const fixedDiv = document.getElementsByClassName("fixed-div")?.[0];
  fixedDiv.append(orders);
}


export const touzhuFunc = (dialogWarpper: HTMLElement) => {
  const SUCCESS = "投注成功";
  const UN_SUCCESS = "投注不成功";
  return new Promise((resolve) => {
    let time = 0;
    const timer = setInterval(() => {
      time++;
      // zjytodo
      if (time > 30) {
        resolve(false);
        return;
      }
      const noSuccess = findElementByTextDFS(dialogWarpper, UN_SUCCESS);
      const successDom = findElementByTextDFS(dialogWarpper, SUCCESS);

      if (noSuccess) {
        clearInterval(timer);
        resolve(UN_SUCCESS);
        return;
      }

      if (successDom) {
        clearInterval(timer);
        resolve(SUCCESS);
        return;
      }
    }, 500);
  });
}